<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体 -->
    <el-card>
      <!--  show-icon 带警告图案 closeable不可关闭 -->
      <el-alert
        title="注意：只允许为第三分类设置参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- mode:选中的值，options:选中要配置的对象, props:配置对象，@chang:mode改变事件 -->
          <el-cascader
            style="margin-left: 15px"
            v-model="selectCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="selectCateChange"
            :collapse-tags="true"
          ></el-cascader>
        </el-col>

        <!-- tab页签区域 -->
        <el-col>
          <el-tabs v-model="activeName" @tab-click="cateTabClick">
            <!-- 添加动态参数面板 -->
            <el-tab-pane label="动态参数" name="many">
              <!-- 添加动态参数按钮 -->
              <el-button
                type="primary"
                size="mini"
                :disabled="isBtnDisabled"
                @click="manyDialog = true"
                >添加参数</el-button
              >
              <!-- 动态参数表格 -->
              <el-table :data="manyDataTable" border stripe>
                <!-- 展开行 -->
                <el-table-column type="expand">
                  <template slot-scope="scoped">
                    <el-tag
                      v-for="(item, i) in scoped.row.attr_vals"
                      :key="i"
                      closable
                      @close="delTag(i, scoped.row)"
                      >{{ item }}</el-tag
                    >
                    <!-- 输入的文本框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scoped.row.inputVisible"
                      v-model="scoped.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scoped.row)"
                      @blur="handleInputConfirm(scoped.row)"
                    >
                    </el-input>
                    <!-- 添加按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scoped.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"> </el-table-column>
                <el-table-column
                  prop="attr_name"
                  label="参数名称"
                ></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scoped">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      size="mini"
                      @click="showEdit(scoped.row)"
                      >编辑</el-button
                    >
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="delParams(scoped.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 添加静态参数面板 -->
            <el-tab-pane label="静态属性" name="only">
              <!-- 添加静态参数按钮 -->
              <el-button
                type="primary"
                size="mini"
                :disabled="isBtnDisabled"
                @click="manyDialog = true"
                >添加属性</el-button
              >
              <!-- 静态参数表格 -->
              <el-table :data="onlyDataTable" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                  <template slot-scope="scoped">
                    <el-tag
                      v-for="(item, i) in scoped.row.attr_vals"
                      :key="i"
                      closable
                      @close="delTag(i, scoped.row)"
                      >{{ item }}</el-tag
                    >
                    <!-- 输入的文本框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scoped.row.inputVisible"
                      v-model="scoped.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scoped.row)"
                      @blur="handleInputConfirm(scoped.row)"
                    >
                    </el-input>
                    <!-- 添加按钮 -->
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scoped.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="#"> </el-table-column>
                <el-table-column
                  prop="attr_name"
                  label="参数名称"
                ></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scoped">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      size="mini"
                      @click="showEdit(scoped.row)"
                      >编辑</el-button
                    >
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="delParams(scoped.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加动态/静态参数Dialog -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="manyDialog"
      width="50%"
      @close="manyDialogClosed()"
    >
      <el-form
        ref="addformRef"
        :model="addform"
        :rules="addformRules"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="manyDialogClosed()">取 消</el-button>
        <el-button type="primary" @click="addParmas()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑按钮Dialog -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="EditDialogVisible"
      width="50%"
      @close="EditDialogClosed()"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditContent()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
//ctrl+d
export default {
  data() {
    return {
      //存储获取的商品列表
      cateList: [],
      //层级选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //层级选择框双向绑定的值
      selectCateKeys: [],
      //被激活标签的名称
      activeName: 'only',
      //动态参数列表
      manyDataTable: [],
      //静态参数列表
      onlyDataTable: [],
      //动态参数对话框的显示与隐藏
      manyDialog: false,
      //添加参数的表单数据对象
      addform: {
        attr_name: '',
      },
      //添加表单的验证规则对象
      addformRules: {
        attr_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
      },
      //编辑对话框的显示与隐藏
      EditDialogVisible: false,
      //编辑对话框的表单数据对象
      editForm: {
        attr_name: '',
        attr_id: '',
      },
      //编辑表单的验证规则对象
      editFormRules: {
        attr_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
      },
      // //控制按钮与文本的切换显示
      // inputVisible: false,
      // //文本框输入的内容
      // inputValue: '',
    }
  },
  methods: {
    //获取商品列表
    async getCateList() {
      //   let getRes = this.$http.get('categories')
      //    getRes.then(function (arr) {
      //     const {data:list}=arr;
      //     console.log(list);
      //   });

      let { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.cateList = res.data
      // console.log(this.cateList);
    },

    //层级选择框框里值发生改变
    selectCateChange() {
      this.getParmasData()
    },
    //点击tabs标签页触发事件
    cateTabClick() {
      this.getParmasData()
    },
    //发起请求 获取参数列表
    async getParmasData() {
      if (this.selectCateKeys.length !== 3) {
        //不是三级函数
        this.selectCateKeys = []
        this.manyDataTable = []
        this.onlyDataTable = []
        return
      }
      //   console.log(this.selectCateKeys)
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('参数列表获取失败')
      }
      console.log(res.data)
      res.data.forEach((item) => {
        //将每一项的attr_val转换成[],判断attr是否为空
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        //对象自定义属性
        //控制文本框的显示与隐藏
        item.inputVisible = false
        //文本框中的值
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyDataTable = res.data
      } else {
        this.onlyDataTable = res.data
      }
    },
    //动态参数对话框关闭事件
    manyDialogClosed() {
      this.$refs.addformRef.resetFields()
      this.manyDialog = false
    },
    //点击确定按钮添加事件
    addParmas() {
      this.$refs.addformRef.validate(async (valid) => {
        if (!valid) {
          //如果为false
          return
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addform.attr_name,
            attr_sel: this.activeName,
          }
        )
        //请求错误
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        //请求成功 更新，关闭dialog
        this.manyDialog = false
        this.getParmasData()
      })
    },
    //显示编辑窗口
    showEdit(value) {
      this.EditDialogVisible = true
      // console.log(value.attr_id);
      this.editForm.attr_name = value.attr_name
      this.editForm.attr_id = value.attr_id
    },
    //编辑对话框确定事件
    async EditContent() {
      // console.log(this.editForm.attr_id);
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('修改失败！！')
      }
      //更新，关闭窗口
      this.EditDialogVisible = false
      this.getParmasData()
    },
    //编辑对话框关闭事件
    EditDialogClosed() {
      this.$refs.editFormRef.resetFields()
      this.EditDialogVisible = false
    },
    //删除参数、属性操作
    async delParams(obj) {
      const decision = await this.$confirm(
        '此操作将' + obj.attr_name + '永久删除, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (decision === 'cancel') {
        this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${obj.attr_id}`
        )
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('删除失败！！')
        }
        this.EditDialogVisible = false
        this.getParmasData()
      }
    },
    //失去焦点/回车事件
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //如果没有return，则证明输入了内容，需要做后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttr_val(row)
    },
    // 编辑提交参数
    async saveAttr_val(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(','),
        }
      )
      // console.log(res);
      console.log(typeof row.attr_vals.join(' '), typeof row.attr_vals)
      if (res.meta.status !== 200) {
        this.$message.error('添加失败')
      }
    },
    //点击按钮，展示文本输入框
    showInput(row) {
      row.inputVisible = true
      //让文本框自动获得焦点
      //$nextTick方法的作用：当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //点击tag标签上的x  i为索引，row为scoped.row
    delTag(i, row) {
      row.attr_vals.splice(i, 1)
      //发起请求
      this.saveAttr_val(row)
    },
  },
  created() {
    this.getCateList()
  },
  ///只要计算属性的()中，所依赖的任何数据发生了改变，则会触发计算属性的重新求值
  computed: {
    isBtnDisabled() {
      if (this.selectCateKeys.length !== 3) {
        return true
      }
      return false
    },
    //当前选中的三级类id
    cateId() {
      if (this.selectCateKeys.length !== 3) {
        return null
      }
      return this.selectCateKeys[2]
    },
    //判断点击的是静态还是动态
    titleText() {
      if (this.activeName === 'many') {
        return '动态属性'
      }
      return '静态属性'
    },
  },
}
</script>
<style scoped>
.cat_opt {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>